<script setup>
/**
 * @author mouse
 * @description 参考调价单，最完美的调价单。
 */
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { saveDeliveryFee, getDeliveryFeeById } from '@/api/goodDeliveryFeeApi'
import { fetchGoodsList } from '@/api/goods'
import GoodsSelector from '@/views/goods-receipt/components/GoodsSelector.vue'
import { useUserStore } from '@/stores/user'
import { getNowDateTime } from '@/utils/dayjs'
import { generatePriceOrderNo } from '@/utils/generateOrderNo'

const emit = defineEmits(['success', 'close'])

const props = defineProps({
  // 配送费调价单ID，用于编辑/详情/审核模式
  deliveryFeeId: {
    type: String,
    default: '',
  },
  isPreview: {
    type: Boolean,
    default: false,
  },
  hideFooter: {
    type: Boolean,
    default: false,
  },
})

const userStore = useUserStore()
const currentUser = computed(() => userStore.nickname || '未登录')
const selectorVisible = ref(false)
const selectedGoods = ref([])
const loading = ref(false)

// 创建默认表单数据
const createDefaultFormData = () => ({
  updateShippingFeeMId: '',
  documentNumber: generatePriceOrderNo(),
  documentTime: getNowDateTime(),
  operatorId: null,
  isCheck: false,
  checkerId: null,
  checkTime: '',
  notes: '',
  operatorName: currentUser.value,
  checkerName: '',
  editType: 0,
  pzUpdateShippingFeeDList: [],
})

// 表单数据
const formData = ref(createDefaultFormData())

// 监听选中的商品变化，更新明细列表
watch(selectedGoods, (newVal) => {
  const existingMap = new Map(
    formData.value.pzUpdateShippingFeeDList.map((item) => [item.dealerGoodsId, item]),
  )
  const newList = newVal.map((good) => {
    const cached = existingMap.get(good.dealerGoodsId)
    if (cached) return cached
    return {
      updateShippingFeeDId: '',
      updateShippingFeeMId: '',
      dealerGoodsId: good.dealerGoodsId,
      freeShipping: good.freeShipping || 0,
      freeShippingNew: good.freeShipping || 0,
      shippingFee: good.shippingFee || 0,
      shippingFeeNew: good.shippingFee || 0,
      goodsName: good.goodsName || good.dealerGoodsName,
      specifications: good.specifications || '',
      unit: good.unit || '',
      goodsPicture: good.goodsPicture || '',
      address: '',
      dealerGoodsTypeId: good.dealerGoodsTypeId || '',
      dealerGoodsTypeCode: good.dealerGoodsTypeCode || '',
      dealerGoodsTypeName: good.dealerGoodsTypeName || '',
    }
  })
  formData.value.pzUpdateShippingFeeDList = newList
})

// 表单验证规则
const rules = {
  documentNumber: [
    { required: true, message: '单据编号不能为空', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
  ],
  pzUpdateShippingFeeDList: [
    { required: true, type: 'array', min: 1, message: '至少添加一件商品', trigger: 'change' },
  ],
}

const formRef = ref(null)

// 初始化表单数据
const initFormData = async () => {
  // 如果有ID，说明是编辑/详情/审核模式，需要从接口获取数据
  if (props.deliveryFeeId) {
    await loadDeliveryFeeData()
  } else {
    // 新增模式，使用默认数据
    resetForm()
  }
}

// 从接口加载配送费调价单数据
const loadDeliveryFeeData = async () => {
  try {
    loading.value = true
    const res = await getDeliveryFeeById(props.deliveryFeeId)
    if (res.success && res.data) {
      const data = res.data
      formData.value = {
        updateShippingFeeMId: data.updateShippingFeeMId || '',
        documentNumber: data.documentNumber || '',
        documentTime: data.documentTime || getNowDateTime(),
        operatorId: data.operatorId || null,
        isCheck: data.isCheck || false,
        checkerId: data.checkerId || null,
        checkTime: data.checkTime || '',
        notes: data.notes || '',
        operatorName: data.operatorName || currentUser.value,
        checkerName: data.checkerName || '',
        editType: data.editType || 0,
        pzUpdateShippingFeeDList: data.pzUpdateShippingFeeDList || [],
      }
      if (
        formData.value.pzUpdateShippingFeeDList &&
        formData.value.pzUpdateShippingFeeDList.length > 0
      ) {
        selectedGoods.value = formData.value.pzUpdateShippingFeeDList.map((item) => ({
          dealerGoodsId: item.dealerGoodsId,
          dealerGoodsName: item.goodsName,
          goodsName: item.goodsName,
          specifications: item.specifications,
          unit: item.unit,
          goodsPicture: item.goodsPicture,
          dealerGoodsTypeName: item.dealerGoodsTypeName,
          freeShipping: item.freeShipping,
          shippingFee: item.shippingFee,
        }))
        fetchGoodsDetails()
      }
    } else {
      ElMessage.error(res.msg || '获取配送费调价单数据失败')
      emit('close')
    }
  } catch (error) {
    logger.error('获取配送费调价单数据失败', error)
    ElMessage.error('获取配送费调价单数据失败')
    emit('close')
  } finally {
    loading.value = false
  }
}

// 获取商品详情
const fetchGoodsDetails = async () => {
  try {
    if (
      !formData.value.pzUpdateShippingFeeDList ||
      formData.value.pzUpdateShippingFeeDList.length === 0
    ) {
      return
    }
    const params = {
      currentPage: 1,
      pageSize: 1000,
      queryFields: {},
    }
    const res = await fetchGoodsList(params)
    if (res.success && res.data && res.data.list) {
      const goodsMap = new Map()
      res.data.list.forEach((good) => {
        goodsMap.set(good.dealerGoodsId, good)
      })
      formData.value.pzUpdateShippingFeeDList = formData.value.pzUpdateShippingFeeDList.map(
        (item) => {
          const goodDetail = goodsMap.get(item.dealerGoodsId)
          if (goodDetail) {
            return {
              ...item,
              goodsName: item.goodsName || goodDetail.goodsName,
              specifications: item.specifications || goodDetail.specifications,
              unit: item.unit || goodDetail.unit,
              goodsPicture: item.goodsPicture || goodDetail.goodsPicture,
              dealerGoodsTypeName: item.dealerGoodsTypeName || goodDetail.dealerGoodsTypeName,
              dealerGoodsTypeId: goodDetail.dealerGoodsTypeId,
              dealerGoodsTypeCode: goodDetail.dealerGoodsTypeCode,
            }
          }
          return item
        },
      )
    }
  } catch (error) {
    logger.error('获取商品详情失败', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 重置表单
const resetForm = () => {
  formData.value = createDefaultFormData()
  selectedGoods.value = []
}

// 打开商品选择器
const openGoodsSelector = () => {
  selectorVisible.value = true
}

// 关闭商品选择器
const handleSelectorClose = () => {
  selectorVisible.value = false
}

// 删除商品
const removeGoods = (item) => {
  const index = formData.value.pzUpdateShippingFeeDList.findIndex((g) => g === item)
  if (index !== -1) {
    formData.value.pzUpdateShippingFeeDList.splice(index, 1)
    selectedGoods.value = selectedGoods.value.filter(
      (g) => String(g.dealerGoodsId) !== String(item.dealerGoodsId),
    )
  }
}

// 表单验证
const validateForm = async () => {
  if (!formRef.value) return false
  if (!formData.value.documentNumber?.trim()) {
    ElMessage.error('单据编号不能为空')
    return false
  }
  if (!formData.value.pzUpdateShippingFeeDList?.length) {
    ElMessage.warning('请至少添加一件商品')
    return false
  }
  try {
    const valid = await formRef.value.validate().catch(() => false)
    if (!valid) {
      ElMessage.error('请填写必填项')
      return false
    }
    // 验证配送费数据
    for (const item of formData.value.pzUpdateShippingFeeDList) {
      if (item.shippingFeeNew < 0 || item.freeShippingNew < 0) {
        ElMessage.warning(`商品 ${item.goodsName} 的配送费不能为负数`)
        return false
      }
      if (!Number.isInteger(Number(item.shippingFeeNew))) {
        ElMessage.warning(`商品 ${item.goodsName} 的新配送费仅支持整数`)
        return false
      }
      if (!Number.isInteger(Number(item.freeShippingNew))) {
        ElMessage.warning(`商品 ${item.goodsName} 的新免配送费数量仅支持整数`)
        return false
      }
    }
    return true
  } catch (error) {
    logger.error('表单验证失败', error)
    ElMessage.error('表单验证失败')
    return false
  }
}

// 提交表单
const submitForm = async (editType) => {
  if (!(await validateForm())) return
  try {
    const submitData = {
      updateShippingFeeMId: formData.value.updateShippingFeeMId,
      documentNumber: formData.value.documentNumber,
      documentTime: formData.value.documentTime,
      operatorId: formData.value.operatorId,
      isCheck: editType === 2,
      checkerId: formData.value.checkerId,
      checkTime: formData.value.checkTime,
      notes: formData.value.notes,
      operatorName: formData.value.operatorName,
      checkerName: formData.value.checkerName,
      editType,
      pzUpdateShippingFeeDList: formData.value.pzUpdateShippingFeeDList.map((item) => ({
        updateShippingFeeDId: item.updateShippingFeeDId,
        dealerGoodsId: item.dealerGoodsId,
        shippingFee: item.shippingFee,
        freeShipping: item.freeShipping,
        shippingFeeNew: item.shippingFeeNew,
        freeShippingNew: item.freeShippingNew,
      })),
    }
    const res = await saveDeliveryFee(submitData)
    if (res.success) {
      ElMessage.success('保存成功')
      emit('success')
      emit('close')
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    logger.error('保存配送费调价单失败', error)
    ElMessage.error('保存配送费调价单失败')
  }
}

// 取消提交
const cancelSubmit = () => {
  emit('close')
}

// 计算属性
const isEdit = computed(() => !!formData.value.updateShippingFeeMId)
const isReadonly = computed(() => props.isPreview)
const hideFooter = computed(() => props.hideFooter)

// 组件挂载时初始化
onMounted(() => {
  initFormData()
})
</script>

<template>
  <!-- 商品选择器对话框 -->
  <el-dialog
    v-model="selectorVisible"
    title="选择需要调整配送费的商品"
    width="80%"
    append-to-body
    align-center
    destroy-on-close
  >
    <GoodsSelector v-model:selectedGoods="selectedGoods" @close="handleSelectorClose" />
  </el-dialog>

  <!-- 配送费调价单表单 -->
  <div class="delivery-fee-container" v-loading="loading">
    <!-- 调价单标题 -->
    <div class="receipt-header">
      <div class="receipt-title">配送费调价单</div>
      <div class="receipt-no">
        <span class="label">NO:</span>
        <el-input
          v-model="formData.documentNumber"
          placeholder="单号已自动生成，可修改"
          class="no-input"
          :disabled="isReadonly"
        />
      </div>
    </div>

    <!-- 表单内容 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="auto"
      class="delivery-fee-form"
    >
      <div class="form-row">
        <el-form-item label="操作人员" prop="operatorName">
          <el-input v-model="formData.operatorName" disabled />
        </el-form-item>
        <el-form-item label="单据时间">
          <el-input v-model="formData.documentTime" disabled />
        </el-form-item>
      </div>
      <div class="form-row">
        <el-form-item label="审核人">
          <el-input v-model="formData.checkerName" disabled placeholder="审核后自动填写" />
        </el-form-item>
        <el-form-item label="审核时间">
          <el-input v-model="formData.checkTime" disabled placeholder="审核后自动填写" />
        </el-form-item>
      </div>
      <div class="form-row">
        <el-form-item label="备注">
          <el-input v-model="formData.notes" placeholder="请输入备注信息" :disabled="isReadonly" />
        </el-form-item>
      </div>
    </el-form>

    <!-- 商品明细 -->
    <div class="goods-section">
      <div class="section-header">
        <h3>商品配送费明细</h3>
        <div class="fee-reminder">新配送费金额仅支持整数，不可输入小数</div>
        <el-button v-if="!isReadonly" type="primary" size="small" @click="openGoodsSelector">
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          添加商品
        </el-button>
      </div>
      <el-table
        :data="formData.pzUpdateShippingFeeDList"
        style="width: 100%"
        class="goods-table"
        :empty-text="'请添加需要调整配送费的商品'"
      >
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="商品图片" width="80" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 40px; height: 40px; border-radius: 4px"
              :preview-src-list="[row.goodsPicture]"
              fit="cover"
              preview-teleported
            />
            <div v-else class="no-image">无图片</div>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="goodsName" min-width="120" align="center" />
        <el-table-column label="规格" prop="specifications" width="100" align="center" />
        <el-table-column label="单位" prop="unit" width="80" align="center" />
        <el-table-column
          label="商品类别"
          prop="dealerGoodsTypeName"
          min-width="100"
          align="center"
        />
        <el-table-column label="原配送费金额(元)" prop="shippingFee" width="140" align="center">
          <template #default="{ row }">
            {{ row.shippingFee }}
          </template>
        </el-table-column>
        <el-table-column label="原免配送费数量(件)" width="150" align="center">
          <template #default="{ row }">
            {{ row.freeShipping || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="新配送费金额(元)" width="150" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.shippingFeeNew"
              :min="0"
              :precision="0"
              :step="1"
              style="width: 100%"
              :disabled="isReadonly"
            />
          </template>
        </el-table-column>
        <el-table-column label="新免配送费数量(件)" width="150" align="center">
          <template #default="{ row }">
            <el-input-number
              v-model="row.freeShippingNew"
              :min="0"
              :precision="0"
              style="width: 100%"
              :disabled="isReadonly"
            />
          </template>
        </el-table-column>
        <el-table-column v-if="!isReadonly" fixed="right" label="操作" width="80" align="center">
          <template #default="{ row }">
            <el-button type="danger" size="small" circle @click="removeGoods(row)">
              <template #icon>
                <el-icon><LineMdTrash /></el-icon>
              </template>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部按钮区域 -->
    <div v-if="!hideFooter" class="footer-actions">
      <template v-if="!isReadonly">
        <el-button @click="cancelSubmit">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button type="primary" @click="submitForm(isEdit ? 1 : 0)">
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          保存调价单
        </el-button>
        <el-button type="success" plain @click="submitForm(2)">
          <template #icon>
            <el-icon><LineMdTabletArrowUp /></el-icon>
          </template>
          保存并审核
        </el-button>
      </template>
      <template v-else>
        <el-button @click="cancelSubmit">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          关闭
        </el-button>
      </template>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.delivery-fee-container {
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: hidden;
}

.receipt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  flex: 0 0 auto;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    bottom: -10px;
    height: 1px;
    border-radius: 10px;
    background-color: #cbcbcb;
  }
  .receipt-title {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }

  .receipt-no {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-left: auto;

    .label {
      font-weight: bold;
      font-size: 16px;
    }

    .no-input {
      width: 200px;
    }
  }
}

.delivery-fee-form {
  flex: 0 0 auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-row {
  display: flex;
  gap: 20px;

  :deep(.el-form-item) {
    flex: 1;
    margin-bottom: 0;
  }
}

.goods-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow: auto;

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: bold;
    }
  }
}

.goods-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .no-image {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    background-color: #f5f7fa;
    font-size: 12px;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
    margin: 0 auto;
  }
}

.footer-actions {
  flex: 0 0 auto;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.fee-reminder {
  color: #e6a23c;
  font-size: 12px;
}
</style>
